<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="'与 ' + ${customer.userName} + ' 的对话 - 客服工作台'">对话 - 客服工作台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        .chat-container {
            height: 500px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 15px;
            background: linear-gradient(to bottom, #f8f9fa, #ffffff);
            position: relative;
        }
        
        .time-divider {
            text-align: center;
            margin: 15px 0;
            position: relative;
        }
        
        .time-divider::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: #e0e0e0;
            z-index: 1;
        }
        
        .time-text {
            background: #ffffff;
            padding: 5px 15px;
            border-radius: 12px;
            font-size: 12px;
            color: #999;
            position: relative;
            z-index: 2;
            display: inline-block;
            border: 1px solid #e0e0e0;
        }
        
        .message-item {
            display: flex;
            margin-bottom: 15px;
            align-items: flex-start;
        }
        
        .message-item.customer {
            flex-direction: row;
        }
        
        .message-item.service {
            flex-direction: row-reverse;
        }
        
        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: white;
            flex-shrink: 0;
            margin: 0 10px;
        }
        
        .avatar.customer {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .avatar.service {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .message-content {
            max-width: 60%;
            position: relative;
        }
        
        .message-bubble {
            padding: 12px 16px;
            border-radius: 18px;
            word-wrap: break-word;
            position: relative;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .message-item.customer .message-bubble {
            background: #ffffff;
            color: #333;
            border: 1px solid #e0e0e0;
            border-bottom-left-radius: 5px;
        }
        
        .message-item.service .message-bubble {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .sender-name {
            font-size: 11px;
            color: #999;
            margin-bottom: 5px;
            padding: 0 5px;
        }
        
        .message-item.service .sender-name {
            text-align: right;
            color: #ccc;
        }
        
        .customer-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .customer-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-right: 15px;
        }
        
        .input-area {
            border-top: 1px solid #e0e0e0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 0 0 10px 10px;
        }
        
        .chat-input {
            border: 1px solid #e0e0e0;
            border-radius: 20px;
            padding: 10px 20px;
            resize: none;
            outline: none;
            box-shadow: none;
        }
        
        .chat-input:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 0.2rem rgba(40,167,69,0.25);
        }
        
        .send-btn {
            border-radius: 20px;
            padding: 10px 25px;
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            border: none;
        }
        
        .send-btn:hover {
            background: linear-gradient(135deg, #218838 0%, #1ea085 100%);
        }
        
        .empty-state {
            text-align: center;
            padding: 50px 20px;
            color: #999;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #ddd;
        }
        
        .conversation-header {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border-radius: 10px 10px 0 0;
            padding: 15px 20px;
            margin: 0;
        }
        
        .status-badge {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
        }
    </style>
</head>
<body>
    <!-- 引入增强版全局通知组件 -->
    <div th:replace="~{common/enhanced-global-notification :: notification}"></div>
<!-- 使用专门的客服导航栏 -->
<div th:replace="~{common/customer-service-navbar :: navbar}"></div>

<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex align-items-center mb-4">
                <a href="/customer-service/conversations" class="btn btn-outline-secondary me-3">
                    <i class="bi bi-arrow-left"></i> 返回对话列表
                </a>
                <div>
                    <h1 class="mb-1">
                        <i class="bi bi-chat-left-text text-success"></i> 客服对话
                    </h1>
                    <small class="text-muted">客服：<span th:text="${username}">您</span></small>
                </div>
            </div>
        </div>
    </div>

    <!-- 错误信息 -->
    <div th:if="${error}" class="alert alert-danger" role="alert">
        <i class="bi bi-exclamation-triangle"></i> <span th:text="${error}">错误信息</span>
    </div>

    <div class="row">
        <div class="col-md-8">
            <!-- 聊天区域 -->
            <div class="card">
                <div class="conversation-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex align-items-center">
                            <div class="customer-avatar me-3">
                                <i class="bi bi-person"></i>
                            </div>
                            <div>
                                <h6 class="mb-1" th:text="'与 ' + ${customer.userName} + ' 的对话'">与顾客的对话</h6>
                                <small class="opacity-75">顾客咨询</small>
                            </div>
                        </div>
                        <span class="badge status-badge">进行中</span>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="chat-container" id="chatContainer">
                        <!-- 空状态 -->
                        <div th:if="${#lists.isEmpty(messages)}" class="empty-state">
                            <i class="bi bi-chat-dots"></i>
                            <h5>暂无对话记录</h5>
                            <p>等待顾客发起对话或开始回复吧！</p>
                        </div>
                        
                        <!-- 消息列表 -->
                        <div th:if="${!#lists.isEmpty(messages)}">
                            <div th:each="message, iterStat : ${messages}">
                                <!-- 时间分隔线 -->
                                <div th:if="${iterStat.first or messages[iterStat.index - 1].createTime != message.createTime}" 
                                     class="time-divider">
                                    <span class="time-text" th:text="${message.createTime}">时间</span>
                                </div>
                                
                                <!-- 消息项 -->
                                <div th:class="${message.isFromCustomer} ? 'message-item customer' : 'message-item service'">
                                    <div th:class="${message.isFromCustomer} ? 'avatar customer' : 'avatar service'">
                                        <i th:class="${message.isFromCustomer} ? 'bi bi-person' : 'bi bi-headset'"></i>
                                    </div>
                                    <div class="message-content">
                                        <div class="sender-name" th:text="${message.senderName}">发送者</div>
                                        <div class="message-bubble" th:text="${message.content}">消息内容</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 输入区域 -->
                <div class="input-area">
                    <form id="messageForm" class="d-flex">
                        <div class="flex-grow-1 me-2">
                            <textarea id="messageInput" class="form-control chat-input" rows="2" 
                                      placeholder="输入您的回复..." required></textarea>
                        </div>
                        <div class="align-self-end">
                            <button type="submit" class="btn btn-success send-btn" id="sendButton">
                                <i class="bi bi-send"></i> 发送
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- 顾客信息侧边栏 -->
        <div class="col-md-4">
            <!-- 顾客信息卡片 -->
            <div class="customer-info-card">
                <div class="d-flex align-items-center mb-3">
                    <div class="customer-avatar">
                        <i class="bi bi-person"></i>
                    </div>
                    <div>
                        <h6 class="mb-1" th:text="${customer.userName}">顾客姓名</h6>
                        <p class="mb-0 opacity-75">在线顾客</p>
                    </div>
                </div>
                <div class="row text-center">
                    <div class="col-12">
                        <h6 class="mb-1">在线</h6>
                        <small class="opacity-75">状态</small>
                    </div>
                </div>
            </div>
            
            <!-- 快速回复 -->
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-lightning"></i> 快速回复</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <button class="btn btn-outline-primary btn-sm" onclick="quickReply('您好！我是客服，有什么可以帮助您的吗？')">
                            问候语
                        </button>
                        <button class="btn btn-outline-primary btn-sm" onclick="quickReply('请稍等，我为您查询一下相关信息。')">
                            查询中
                        </button>
                        <button class="btn btn-outline-primary btn-sm" onclick="quickReply('感谢您的咨询，还有其他问题吗？')">
                            询问其他
                        </button>
                        <button class="btn btn-outline-primary btn-sm" onclick="quickReply('感谢您的咨询，祝您购物愉快！')">
                            结束语
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 操作面板 -->
            <div class="card mt-3">
                <div class="card-header">
                    <h6 class="mb-0"><i class="bi bi-tools"></i> 操作面板</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="/customer-service/conversations" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-list"></i> 对话列表
                        </a>
                        <a href="/customer-service/dashboard" class="btn btn-outline-info btn-sm">
                            <i class="bi bi-house"></i> 工作台
                        </a>
                    </div>
                    
                    <hr>
                    
                    <div class="text-center">
                        <small class="text-muted">
                            <i class="bi bi-info-circle"></i> 
                            支持 Ctrl+Enter 快速发送
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script th:inline="javascript">
    const conversationId = /*[[${conversationId}]]*/ '';
    let currentMessageCount = /*[[${#lists.size(messages)}]]*/ 0;
    let pollInterval;
    
    document.addEventListener('DOMContentLoaded', function() {
        const messageForm = document.getElementById('messageForm');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const chatContainer = document.getElementById('chatContainer');
        
        // 滚动到底部
        scrollToBottom();
        
        // 开始轮询检查新消息
        startPolling();
        
        // 页面离开时停止轮询
        window.addEventListener('beforeunload', function() {
            stopPolling();
        });
        
        // 处理表单提交
        messageForm.addEventListener('submit', function(e) {
            e.preventDefault();
            sendMessage();
        });
        
        // 支持Ctrl+Enter发送
        messageInput.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // 自动聚焦到输入框
        messageInput.focus();
        
        // 标记消息为已读
        markMessagesRead();
    });
    
    function startPolling() {
        pollInterval = setInterval(function() {
            checkForNewMessages();
        }, 2000); // 每2秒检查一次，更及时
    }
    
    function stopPolling() {
        if (pollInterval) {
            clearInterval(pollInterval);
        }
    }
    
    function checkForNewMessages() {
        // 首先检查对话状态
        checkConversationStatus();
        
        fetch('/customer-service/get-messages/' + conversationId)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.messages) {
                    const newMessageCount = data.messages.length;
                    console.log('检查消息：当前消息数：' + currentMessageCount + '，新消息数：' + newMessageCount);
                    
                    if (newMessageCount !== currentMessageCount) {
                        // 消息数量发生变化，动态更新界面
                        console.log('消息数量变化，更新界面');
                        updateMessageList(data.messages);
                        
                        // 如果消息增加，检查是否为用户新消息
                        if (newMessageCount > currentMessageCount) {
                            // 检查最新消息是否来自用户
                            const latestMessage = data.messages[data.messages.length - 1];
                            if (latestMessage && latestMessage.isFromCustomer) {
                                showNewMessageNotification();
                            }
                        }
                        
                        currentMessageCount = newMessageCount;
                    }
                } else if (!data.success && (data.message.includes('对话不存在') || data.message.includes('无权限访问'))) {
                    // 对话已被用户结束
                    showConversationClosedNotification();
                    stopPolling(); // 停止轮询
                    setTimeout(() => {
                        window.location.href = '/customer-service/conversations';
                    }, 3000);
                }
            })
            .catch(error => {
                console.error('检查新消息失败:', error);
            });
    }
    
    function checkConversationStatus() {
        fetch('/customer-service/api/conversation-status/' + conversationId)
            .then(response => response.json())
            .then(data => {
                if (!data.success || !data.exists || (data.exists && data.status === 'closed')) {
                    // 对话不存在或已结束
                    showConversationClosedNotification();
                    stopPolling();
                    disableMessageInput(); // 禁用输入框
                    setTimeout(() => {
                        window.location.href = '/customer-service/conversations';
                    }, 3000);
                }
            })
            .catch(error => {
                console.error('检查对话状态失败:', error);
            });
    }
    
    function disableMessageInput() {
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const messageForm = document.getElementById('messageForm');
        
        if (messageInput) {
            messageInput.disabled = true;
            messageInput.placeholder = '对话已结束，无法发送消息';
        }
        if (sendButton) {
            sendButton.disabled = true;
            sendButton.innerHTML = '<i class="bi bi-x-circle"></i> 对话已结束';
        }
        if (messageForm) {
            messageForm.style.opacity = '0.5';
        }
    }
    
    function sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const message = messageInput.value.trim();
        
        if (!message) {
            return;
        }
        
        // 禁用发送按钮
        sendButton.disabled = true;
        sendButton.innerHTML = '<i class="bi bi-hourglass-split"></i> 发送中...';
        
        // 发送消息
        fetch('/customer-service/send-message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                conversationId: conversationId,
                message: message
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清空输入框
                messageInput.value = '';
                // 更新消息列表
                if (data.messages) {
                    updateMessageList(data.messages);
                    currentMessageCount = data.messages.length;
                }
            } else {
                alert('发送失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('发送失败，请重试');
        })
        .finally(() => {
            // 恢复发送按钮
            sendButton.disabled = false;
            sendButton.innerHTML = '<i class="bi bi-send"></i> 发送';
        });
    }
    
    function updateMessageList(messages) {
        const chatContainer = document.getElementById('chatContainer');
        
        // 查找现有的消息容器，如果没有则创建
        let messagesContainer = chatContainer.querySelector('.messages-container');
        if (!messagesContainer) {
            // 清空聊天容器并创建新的消息容器
            chatContainer.innerHTML = '';
            messagesContainer = document.createElement('div');
            messagesContainer.className = 'messages-container';
            chatContainer.appendChild(messagesContainer);
        } else {
            // 清空现有消息
            messagesContainer.innerHTML = '';
        }
        
        if (messages.length === 0) {
            // 显示空状态
            messagesContainer.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-chat-dots"></i>
                    <h5>暂无对话记录</h5>
                    <p>等待顾客发起对话或开始回复吧！</p>
                </div>
            `;
            return;
        }
        
        let lastDate = '';
        messages.forEach(function(message, index) {
            // 检查是否需要显示时间分隔符
            const currentTime = message.createTime;
            const showTimeDivider = index === 0 || (index > 0 && messages[index - 1].createTime !== currentTime);
            
            if (showTimeDivider) {
                const timeDivider = document.createElement('div');
                timeDivider.className = 'time-divider';
                timeDivider.innerHTML = '<span class="time-text">' + currentTime + '</span>';
                messagesContainer.appendChild(timeDivider);
            }
            
            // 创建消息元素
            const messageItem = document.createElement('div');
            messageItem.className = message.isFromCustomer ? 'message-item customer' : 'message-item service';
            
            messageItem.innerHTML = `
                <div class="${message.isFromCustomer ? 'avatar customer' : 'avatar service'}">
                    <i class="${message.isFromCustomer ? 'bi bi-person' : 'bi bi-headset'}"></i>
                </div>
                <div class="message-content">
                    <div class="sender-name">${message.senderName}</div>
                    <div class="message-bubble">${message.content}</div>
                </div>
            `;
            
            messagesContainer.appendChild(messageItem);
        });
        
        // 滚动到底部
        scrollToBottom();
    }
    
    function quickReply(text) {
        const messageInput = document.getElementById('messageInput');
        messageInput.value = text;
        messageInput.focus();
    }
    
    function scrollToBottom() {
        const chatContainer = document.getElementById('chatContainer');
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
    
    
     
           function markMessagesRead() {
          fetch('/customer-service/mark-messages-read', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                  conversationId: conversationId
              })
          })
          .then(response => response.json())
          .catch(error => {
              console.error('标记已读失败:', error);
          });
      }
      
      function showConversationClosedNotification() {
          // 创建通知元素
          const notification = document.createElement('div');
          notification.className = 'alert alert-warning alert-dismissible fade show position-fixed';
          notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 350px;';
          notification.innerHTML = `
              <i class="bi bi-exclamation-triangle"></i>
              <strong>对话已结束</strong>
              <p class="mb-0">用户已结束此对话，3秒后将返回对话列表</p>
              <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
          `;
          
          document.body.appendChild(notification);
          
          // 5秒后自动移除通知
          setTimeout(() => {
              if (notification.parentNode) {
                  notification.parentNode.removeChild(notification);
              }
          }, 5000);
      }
      
      function showNewMessageNotification() {
          // 创建新消息通知
          const notification = document.createElement('div');
          notification.className = 'alert alert-info alert-dismissible fade show position-fixed';
          notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
          notification.innerHTML = `
              <i class="bi bi-chat-left-text"></i>
              <strong>新消息</strong>
              <p class="mb-0">用户发送了新消息</p>
              <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
          `;
          
          document.body.appendChild(notification);
          
          // 3秒后自动移除通知
          setTimeout(() => {
              if (notification.parentNode) {
                  notification.parentNode.removeChild(notification);
              }
          }, 3000);
      }
      

</script>
</body>
</html> 